"""
Manage automatically playing podcasts.
"""
from .log import log
from .gui.app import GuiApp
from .gui.form.button import MultiStateButton
from .gui.form.dynamicposition import HBox
from .gui.form.dynamicposition import FormWidth
from .gui.form.dynamicposition import DynamicPosition
from .podcast import listen
import play
import playscreen

class AutoPlayScreen(playscreen.BasePlayScreen):
  """Add buttons specific to auto-play."""
  def __init__(self, app, current_song):
    playscreen.BasePlayScreen.__init__(self, app, current_song)
    self._AddAutoPlayUiElements()
    self.CommitLayout("autoplay")

  def _AddAutoPlayUiElements(self):
    hbox_dp = HBox(hcenter=FormWidth(self._layout), below=self._play_button_dp,
        vspacing=(80, 0))

    # This sucks button
    self._sucks_button, sucks_button_dp = self._AddButton("This Sucks",
        self._ThisSucks, None, hbox_dp)
    self._notnow_button, notnow_button_dp = self._AddButton("Not Now",
        self._NotNow, sucks_button_dp, hbox_dp)
    self.CreateMarkListenedButton(hbox_dp)

    button_dp = DynamicPosition(self._mark_listened_button,
        right_of=notnow_button_dp, vcenter=hbox_dp, hspacing=(0, 10))
    self._layout.AddItem(button_dp)
    hbox_dp.AddChild(button_dp)

    self._layout.AddItem(hbox_dp)

  def _ThisSucks(self):
    log("*********** THIS SUCKS")
    self._SetSkippedAndAutoPlay()

  def _NotNow(self):
    log("*********** NOT NOW")
    self.AutoPlay()

  def _SetListenedAndAutoPlay(self):
    """Set the current episode's listened attribute and autoplay the next
    podcast in the queue."""
    self._current_song.feed.SetListened(self._current_song.episode)
    self.AutoPlay()

  def _SetSkippedAndAutoPlay(self):
    """Set the current episode's listened attribute and autoplay the next
    podcast in the queue."""
    self._current_song.feed.SetSkipped(self._current_song.episode)
    self.AutoPlay()

  def AutoPlay(self):
    """Pick a podcast feed to play and begin playing the newest unlistened
    episode from it."""
    # Note that Recommend() updates the last-chosen-time stat.
    feed = listen.Recommend()
    if not feed:
      self._app.SetCurrentScreen("main menu", GuiApp.ENTER_FROM_RIGHT)
      return

    episode = feed.GetNextUnlistenedEpisode()
    self.PlayEpisode(feed, episode, lambda: self._SetListenedAndAutoPlay(),
        "main menu")
